package com.itany.shop.service.impl;
import com.itany.shop.dao.UserDao;
import com.itany.shop.entity.User;
import com.itany.shop.exception.CodeErrorException;
import com.itany.shop.exception.RequestParameterErrorException;
import com.itany.shop.exception.UserExistException;
import com.itany.shop.exception.UserNotExistException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.service.UserService;
import com.itany.shop.util.MD5Util;
import com.itany.shop.util.ParameterUtil;

/**
 * @author MissChen
 * @date 2024年03月29日 9:47
 */
public class UserServiceImpl implements UserService {
    private UserDao userDao = (UserDao) ObjectFactory.getObject("userDao");

    @Override
    public void register(String username, String password, String phone, String address) throws RequestParameterErrorException, UserExistException {
        //业务层对获取的数据做一个非空校验
        if (ParameterUtil.isNull(username) || ParameterUtil.isNull(password) || ParameterUtil.isNull(phone) || ParameterUtil.isNull(address)) {
            throw new RequestParameterErrorException("请求参数有误");
        }

        //根据用户名查找用户是否已经存在
        User selectUser = userDao.selectByUsername(username);

        //如果查到对应的用户，说明该用户已经存在，抛出异常
        if (selectUser != null) {
            throw new UserExistException("该用户已经存在");
        }

        //如果用户名可用，则直接添加
        //对于密码需要加密后进行保存
        User user = new User(username, MD5Util.md5(password), phone, address);

        //调用dao方法执行添加操作
        userDao.insertUser(user);


    }

    @Override
    public User login(String username, String password) throws RequestParameterErrorException, UserNotExistException {
        if(ParameterUtil.isNull(username)||ParameterUtil.isNull(password)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        User user=userDao.selectByUsernameAndPassword(username,MD5Util.md5(password));
        if(null==user){
           throw new UserNotExistException("用户名或密码错误");
        }
        return user;

    }

    @Override
    public User login(String username, String password, String code, String imageCode) throws RequestParameterErrorException, UserNotExistException, CodeErrorException {
        if(ParameterUtil.isNull(username)||ParameterUtil.isNull(password) ||ParameterUtil.isNull(code)||ParameterUtil.isNull(imageCode)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        if(!code.equals(imageCode)){
            throw new CodeErrorException("验证码不正确");
        }
        User user=userDao.selectByUsernameAndPassword(username,MD5Util.md5(password));
        if(null==user){
            throw new UserNotExistException("用户名或密码错误");
        }
        return user;
    }
}
